//
//  PersonalCenterViewController.m
//  IntegralDog
//
//  Created by wmm on 16/1/21.
//  Copyright © 2016年 hanen. All rights reserved.
//

#import "PersonalCenterViewController.h"
#import "QRCodeGenerator.h"
#import "Macro.h"
#import "IntegralStoreViewController.h"
#import "DownloadHistoryViewController.h"
#import "RankingTableViewController.h"
#import "PCTableViewCell.h"
#import "SettingViewController.h"
#import "UIImageView+WebCache.h"
#import "PersonalNetTool.h"
#import "personalModel.h"

@interface PersonalCenterViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate>{
   
    
}

@property (nonatomic, strong) UIImageView *headerImageView;
@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *phoneLabel;

@property (strong , nonatomic) UIImage *qRImage;

@property (nonatomic, strong) UILabel *integralLabel;

@end

@implementation PersonalCenterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBarHidden = YES;
//    self.navigationItem.backBarButtonItem.title = @"";
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self initWithViews];
}



#pragma mark
#pragma mark --actionSheet delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self takePhotoFromLibrary];
    }else if (buttonIndex == 1){
        [self takePhotoFromCamera];
    }
}
- (void)takePhotoFromLibrary{
    UIImagePickerController *imagePick = [[UIImagePickerController alloc] init];
    imagePick.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePick.delegate = self;
    imagePick.allowsEditing = YES;
    [self presentViewController:imagePick animated:YES completion:nil];
}
- (void)takePhotoFromCamera{
    UIImagePickerController *imagePic = [[UIImagePickerController alloc]init];
    imagePic.sourceType = UIImagePickerControllerSourceTypeCamera;
    imagePic.delegate = self;
    imagePic.allowsEditing = YES;
    [self presentViewController:imagePic animated:YES completion:nil];
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    _headerImageView.image = image;
    NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
    NSString *str = [imageData base64Encoding];
    
    NSDictionary * dic =@{@"token":TOKEN,@"uid":@(UID),@"logo":str};
    [DataTool postWithUrl:UPDARE_LOGO_URL parameters:dic success:^(id data) {
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@+++++--",jsonDic);
        
        
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
    
}
#pragma mark
#pragma mark------修改头像
- (void)changeHeaderButton
{
//    UIActionSheet *sheet;
//    sheet = [[UIActionSheet alloc] initWithTitle:@"选择图像" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"从相册选择", nil];
//    sheet.tag = 255;
//    [sheet showInView:self.view];
    if([[[UIDevice currentDevice] systemVersion] floatValue] == 7){
        UIActionSheet * actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从相册选择",@"打开相机", nil];
        [actionSheet showInView:self.view];
    }else{
        UIAlertController * alertionControll = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [self takePhotoFromLibrary];
        }];
        UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"打开相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [self takePhotoFromCamera];
        }];
        UIAlertAction * action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertionControll addAction:action1];
        [alertionControll addAction:action2];
        [alertionControll addAction:action3];
        if(alertionControll != nil){
            [self presentViewController:alertionControll animated:YES completion:nil];
        }
    }

}
- (void)actionSheetCancel:(UIActionSheet *)actionSheet
{
    [actionSheet dismissWithClickedButtonIndex:2 animated:YES];
}

//#pragma mark - action sheet delegte  
//- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
//    if (actionSheet.tag == 255) {          NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;         // 判断是否支持相机
//        if([UIImagePickerController  isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
//            switch (buttonIndex) {
//                case 0:
//                    return;
//                case 1:
//                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//                break;             }         }
//        else {
//            if (buttonIndex == 0) {
//                return;             }
//            else {
//                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
//            }
//        }
//        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
//        imagePickerController.delegate = self;
//        imagePickerController.allowsEditing = YES;
//        imagePickerController.sourceType = sourceType;
//        [self presentViewController:imagePickerController animated:YES completion:^{}];
//    }
//}
//
//#pragma mark - image picker delegte
//- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
//    [picker dismissViewControllerAnimated:YES completion:^{
//}];
//    UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
//    _headerImageView.image = image;
//    NSData *imageData = UIImageJPEGRepresentation(image, 0.7);
//
//   // NSString *norPicPath = [self dataPath:[NSString stringWithFormat:@"%@.png",@"header"]];
//   // NSLog(@"filepath: %@",imageData);
//    
////    BOOL file = [imageData writeToFile:norPicPath atomically:YES];
////    if (file) {
//        [PersonalNetTool UpdateHeaderWithLogo:@"logo" filepath:imageData complationBlock:^(NSDictionary *dic) {
//            NSLog(@"头像修改成功");
//            
//        }];
//   // }
//}
//
//- (NSString *)dataPath:(NSString *)file
//{
//    NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"user"];
//    NSLog(@",,,,   %@",path);
//    [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
//    NSString *result = [path stringByAppendingPathComponent:file];
//    return result;
//}

- (void)initWithViews
{
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 230)];
    
    UIImageView *topBgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 230)];
    topBgView.image = [UIImage imageNamed:@"uc_Yonghu.png"];
    topBgView.userInteractionEnabled = YES;
    [headerView addSubview:topBgView];
    
    
    _headerImageView = [[UIImageView alloc]initWithFrame:CGRectMake((kScreenWidth - 100)/2, 40, 100, 100)];
    _headerImageView.layer.cornerRadius = 50;
    _headerImageView.clipsToBounds = YES;
    
    UIButton *changeHeader = [[UIButton alloc] init];
    changeHeader.center = CGPointMake(kScreenWidth/2.0, 100);
    changeHeader.bounds = CGRectMake(0, 0, 100, 100);
    [changeHeader addTarget:self action:@selector(changeHeaderButton) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:_headerImageView];
    [topBgView addSubview:changeHeader];
    
    
    _nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, _headerImageView.maxY + 20, kScreenWidth, 30)];
    _nameLabel.textAlignment = NSTextAlignmentCenter;
    _nameLabel.numberOfLines = 0;
    _nameLabel.lineBreakMode = NSLineBreakByWordWrapping;
    
    _nameLabel.textColor = [UIColor whiteColor];
    _nameLabel.font = [UIFont boldSystemFontOfSize:20];
    [headerView addSubview:_nameLabel];
    
    _phoneLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, _nameLabel.maxY, kScreenWidth, 30)];
    _phoneLabel.textAlignment = NSTextAlignmentCenter;
    _phoneLabel.numberOfLines = 0;
    _phoneLabel.lineBreakMode = NSLineBreakByWordWrapping;
    
    _phoneLabel.textColor = [UIColor whiteColor];
    _phoneLabel.font = [UIFont systemFontOfSize:18];
    [headerView addSubview:_phoneLabel];
    
    [PersonalNetTool getPersonalcomplationBlock:^(NSDictionary *dic) {
        NSDictionary *dictionary = [DataTool changeType:dic];
        
        personalModel *model = [[personalModel alloc] initWithDictionary:dictionary];
        if ([model.logo isEqualToString:@""] | (model.logo.length == 0)) {
            [_headerImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMAGEURL,model.logo]] placeholderImage:[UIImage imageNamed:@"uc_Touxiang"]];
        }else{
            [_headerImageView setImage:[UIImage imageNamed:@"uc_Touxiang"]];
        }
        if ([model.nickname isEqualToString:@""] | (model.nickname.length == 0)) {
            _nameLabel.text = model.nickname;
        }
//        if ([model.telphone isEqualToString:@""] | (model.telphone.length == 0)) {
            _phoneLabel.text = model.telphone;
//        }
        
//        [_headerImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMAGEURL,model.logo]] placeholderImage:[UIImage imageNamed:@"uc_Touxiang"]];
//        _nameLabel.text = model.nickname;
//        _phoneLabel.text = model.telphone;
        
    }];
    //加号图片
    UIImageView *qRPlusView = [[UIImageView alloc]initWithFrame:CGRectMake(kScreenWidth - 70, _nameLabel.y, 10, 10)];
    
    qRPlusView.image = [UIImage imageNamed:@"uc_Jiahao.png"];
    [headerView addSubview:qRPlusView];
    
    
    UIImageView *qRBgView = [[UIImageView alloc]initWithFrame:CGRectMake(qRPlusView.maxX - 4, qRPlusView.maxY - 4, 50, 50)];
    qRBgView.image = [UIImage imageNamed:@"uc_Tuoyuan.png"];
    [headerView addSubview:qRBgView];
    
    
    _qRImage = [QRCodeGenerator qrImageForString:@"积分狗" imageSize:80];
    
    UIImageView *qRImageView = [[UIImageView alloc]initWithFrame:CGRectMake(qRBgView.x + 5, qRBgView.y + 5, 40, 40)];
    [qRImageView setImage:_qRImage];
    [headerView addSubview:qRImageView];
    //设置按钮
    UIButton *moreBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    // btn.frame = rect_screen;
    moreBtn.frame = CGRectMake(kScreenWidth-50, 40, 25, 25);
    [moreBtn setImage:[UIImage imageNamed:@"uc_Shezhi.png"] forState:UIControlStateNormal];
    [moreBtn addTarget:self action:@selector(moreButClick) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:moreBtn];
    
    
    UITableView *ucTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, headerView.maxY, kScreenWidth , kScreenHeight - headerView.maxY -60) style:UITableViewStylePlain];
    ucTableView.backgroundColor = bGGrayColor;
    ucTableView.delegate=self;
    ucTableView.dataSource=self;
    ucTableView.separatorStyle = UITableViewCellSelectionStyleNone;
    //ucTableView.scrollEnabled =NO;
    
    [self.view addSubview:headerView];
    //ucTableView.tableHeaderView = headerView;
    [self.view addSubview:ucTableView];
    
}

- (void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden = YES;
        self.tabBarController.hidesBottomBarWhenPushed = NO;
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.tabBarController.hidesBottomBarWhenPushed = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    static NSString *iden=@"cell";
//    UITableViewCell * cell=[tableView dequeueReusableCellWithIdentifier:iden];
//    if (cell==nil)
//    {
//        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:iden];
//    }
    static NSString *CellIdentifier = @"PCTableViewCell";
    PCTableViewCell *cell = (PCTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[PCTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    
//    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    NSLog(@"%ld",(long)indexPath.row);
    
    if(indexPath.section == 0){
        cell.pcImgView.image = [UIImage imageNamed:@"uc_Jifenchoujiang.png"];
        cell.pcNameLab.text = @"积分抽奖";
    }
    if(indexPath.section == 1){
        cell.pcImgView.image = [UIImage imageNamed:@"uc_Jifen.png"];
        cell.pcNameLab.text = @"积分签到";
    }
    if(indexPath.section == 2){
        cell.pcImgView.image = [UIImage imageNamed:@"uc_Paihangbang.png"];
        cell.pcNameLab.text = @"排行榜";
    }
    if(indexPath.section == 3){
        cell.pcImgView.image = [UIImage imageNamed:@"uc_Jilu.png"];
        cell.pcNameLab.text = @"下载记录";
    }
    if(indexPath.section == 4){
        cell.pcImgView.image = [UIImage imageNamed:@"uc_Zhinengkefu.png"];
        cell.pcNameLab.text = @"智能客服";
    }
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if(indexPath.section == 0){
        
//        IntegralStoreViewController *vc = [[IntegralStoreViewController alloc] init];
//        vc.IntegralNum = @"10000";
//        [self.navigationController pushViewController:vc animated:YES];
//        NSLog(@"push ");
    }
    if(indexPath.section == 2){
        RankingTableViewController *vc = [[RankingTableViewController alloc] init];
        [self.navigationController pushViewController:vc animated:NO];

    }
    if(indexPath.section == 3){
        DownloadHistoryViewController *vc = [[DownloadHistoryViewController alloc] init];
        [self.navigationController pushViewController:vc animated:NO];
        
    }

}

-(void)moreButClick{
    SettingViewController *vc = [[SettingViewController alloc] init];
    [self.navigationController pushViewController:vc animated:NO];
}

@end
